<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule\ModulesModule;


use Nette\Environment;
use Albireo\Forms\AlbireoForm;

use KernelModule\BasePresenter;
use Celebrio\Core\ServiceProvider;
use Celebrio\Modules;
use dibi;

/**
 * Kernel modules management presenter.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class ConsolePresenter extends BasePresenter {

    /**
     * startup is always called
     */
    public function startup() {
        parent::startup();
        $this->showMenu();
    }


    public function actionDefault() {
        $database = ServiceProvider::getService(Modules::DB);
        $namespace = $this->getSession("console");
        if (isset($namespace->queries)) {
            $this->template->queries = $namespace->queries;
        }
        $this->template->database = $database;
        $this->template->title = ServiceProvider::getServiceName(Modules::DB) . " " . _("Console");
    }

    protected function createComponentConsole() {
        $form = new AlbireoForm();
        $form->addTextArea("albireoConsole", ServiceProvider::getServiceName(Modules::DB) . ">", NULL, 1);
        $form->addSubmit('process', _('Process'));
        $form->onSubmit[] = callback($this, 'processQuery');
        return $form;
    }

    public function processQuery($form) {
        $values = $form->values;
        $this->callConsole($values['albireoConsole']);
    }

    private function callConsole($query) {
        $namespace = $this->getSession("console");
        if (isset($namespace->queries)) {
            $namespace->queries[] = $query;
        } else {
            $namespace->queries = array($query);
        }
        $this->template->queries = $namespace->queries;
        $this->template->console = $this->console($query);
    }

    public function handleProcess($query) {
        $query = htmlspecialchars($query);
        $this->invalidateControl("console");
        $this->invalidateControl("list"); // should this be here?
        $this->callConsole($query);
    }

    public function console($query) {
        try {
            $result = dibi::nativeQuery($query);
            $return = "<div>" . _("Query time:") . " " . dibi::$elapsedTime . "</div>";
            if ($result instanceof \DibiResult) {
//                if (!$result->fetch()) {
//                    return $return;
//                }
                $return .= "\n<table class='dbtable'>\n<thead>\n<tr>";
                foreach ($result->getInfo()->getColumnNames() as $colName) {
                    $return .= "<th>" . $colName . "</th>";
                }
                $return .= "</tr>\n</thead>\n<tbody>\n";
                foreach ($result as $row) {
                    $return .= "<tr>";
                    foreach ($row as $cell) {
                        $cell = $this->handleNonstringTypes($cell);
                        $return .= "<td>" . nl2br(htmlspecialchars($cell)) . "</td>";
                    }
                    $return .= "</tr>\n";
                }

                $return .= "</tbody>\n</table>";
                unset($result);
            } else {
                $return.= "<div>" . sprintf(ngettext("%s affected row.", "%s affected rows.", $result), $result) . "</div>";
            }
            //return $result->getRowClass();
            return $return;
        } catch (\DibiException $e) {
            return '<div>' . sprintf(_("Error number %s in your SQL command:"), $e->getCode()) . ' <strong>' . $e->getSql() . '</strong> <br /> <strong>' . $e->getMessage() . '</strong> </div>';
        }
    }

    private function handleNonstringTypes($cell) {
        if ($cell instanceof \DateTime) return $cell->format("d.m.Y H:i:s");
        if ($cell === true) return "yes";
        if ($cell === false) return "no";
        if ($cell === null) return "<<null>>";
        return $cell;
    }


}